# -*- coding: utf-8 -*-
import base64
import StringIO
# import csv
import datetime
import xlwt
import xlrd

from openerp.osv import osv, fields


class apply_export_wizard(osv.osv):
    _name = 'apply.export.wizard'
    _columns = {
        'selected': fields.integer(u'当前已选', readonly=1),
        'exported': fields.integer(u'之前已导出', readonly=1),
        'filename': fields.char(u'文件名', readonly=1),
        'data': fields.binary(u'文件', readonly=1),
        'state': fields.selection([('1', '1'), ('2', '2')], string=u'状态'),
    }
    _defaults = {
        'selected': lambda s, c, u, ctx: len(ctx.get('active_ids')),
        'state': '1',
    }

    def button_next(self, cr, uid, ids, context=None):
        delivery_obj = self.pool.get('apply.delivery')
        if context is None:
            context = {}
        if isinstance(ids, int):
            this_id = ids
        else:
            this_id = ids[0]
        xls = StringIO.StringIO()
        # 发货记录导出的字段 [卡号 产品 快递单号 快递方式 联系人 省 市 县 街道 手机 电话 期望发货日期]
        xls_workbook = xlwt.Workbook(encoding="utf8")
        data_sheet = xls_workbook.add_sheet('data')
        selected = context.get('active_ids')
        to_export_ids = delivery_obj.search(
            cr, uid, [('is_export', '=', False), ('id', 'in', selected)], context=context)
#         if not to_export_ids:
#             raise osv.except_osv(u'错误',u'所选发货记录已全部被导出过，请重新选择')
        exported = len(context.get('active_ids')) - len(to_export_ids)
        # write header first
        field_names = ['copy_code', 'product_id', 'to_name', 'province', 'city', 'country', 'address', 'phone_number', 'mobile_number',
                       'estimated_ship_date', 'client_name', 'shipping_type', 'shipping_code', 'shop_express_fee', 'subsidy']
        header = [u"卡号", u"产品", u"联系人", u"省", u"市", u"县", u"街道",
                  u"电话号码", u"手机号码", u"期望发货日期", u'渠道', u"快递方式", u"快递单号", u"运费补助", u"产品补助费"]
        length = len(header) - 2
        user_objs = self.pool.get('res.users').browse(
            cr, uid, uid, context=context)
        if user_objs[0].has_group('dzx_ext.group_stores'):
            length = len(header)
            #如果是门店,需要检查记录是否被接受
            shop_no_accept_ids = delivery_obj.search(cr, uid, [('is_shop_accept', '=', False), ('id', 'in', selected)], context=context)
            if shop_no_accept_ids:
                raise osv.except_osv(u'错误', u'含有没有接受的订单记录, 不能进行导出操作')
        for i in range(length):
            data_sheet.write(0, i, header[i])

        export_data = delivery_obj.export_data(
            cr, uid, selected, [field_names[name] for name in xrange(length)], context=context).get('datas', [])
        row = 1
        for record in export_data:
            for i in range(len(record)):
                if record[i]:
                    export_value = str(record[i])    # 将数字转成字符串，以免被excel变成科学计数法
                    data_sheet.write(row, i, export_value)
            row += 1

        xls_workbook.save(xls)
        xls.seek(0)
        out = base64.encodestring(xls.getvalue())
        vals = {'data': out,
                'filename': u'deliery_export_%s.xls' % datetime.datetime.now().strftime("%Y%m%d"),
                'state': '2',
                'exported': exported}
        self.write(cr, uid, ids, vals, context=context)
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'apply.export.wizard',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': this_id,
            'views': [(False, 'form')],
            'target': 'new',
        }


class apply_import_wizard(osv.osv):
    _name = 'apply.import.wizard'
    _columns = {
        'selected': fields.integer(u'总导入条数', readonly=1),
        'imported': fields.integer(u'有效条数', readonly=1),
        'to_import': fields.text(u'需导入的有效条目'),
        'data': fields.binary(u'请选择文件上传'),
        'state': fields.selection([('1', '1'), ('2', '2')], string=u'状态'),
    }
    _defaults = {
        'state': '1',
    }

    def button_next(self, cr, uid, ids, context=None):
        delivery_obj = self.pool.get('apply.delivery')
        express_obj = self.pool.get('express.type')
        user_obj = self.pool.get('res.users')
        if context is None:
            context = {}
        if isinstance(ids, int):
            this_id = ids
        else:
            this_id = ids[0]
        this = self.browse(cr, uid, ids, context)[0]
        # 发货记录导出的字段 [卡号 产品 快递单号 快递方式 联系人 省 市 县 街道 手机 电话 期望发货日期]
        xls_file = StringIO.StringIO(base64.decodestring(this.data))
        workbook = xlrd.open_workbook(file_contents=xls_file.read())
        worksheet = workbook.sheets()[0]
        header = [u"卡号", u"产品", u"联系人", u"省", u"市", u"县", u"街道",
                  u"电话号码", u"手机号码", u"期望发货日期", u'渠道', u"快递方式", u"快递单号", u'运费补助', u'产品补助费']
        selected = 0  # 导入文件的总行数（不包含header行）
        to_import = []  # 有效的行数（已输入了快递单号和快递方式，且erp中未记录发货的）

        length = len(header) - 2
        user_objs = self.pool.get('res.users').browse(
            cr, uid, uid, context=context)
        if user_objs[0].has_group('dzx_ext.group_stores'):
            length = len(header)

        nrows = worksheet.nrows
        for i in range(nrows):
            selected += 1
            record = worksheet.row_values(i)
            # 验证首行是否与导出文件一致
            if i == 0:
                if record != [header[name] for name in xrange(length)]:
                    raise osv.except_osv(u'错误', u'文件格式有误，请重新上传')
            else:
                # 忽略未输入快递方式的
                if not record[header.index(u'快递方式')]:
                    continue
                # excel中输入的快递方式在系统里查不到，需要用户修正
                if not express_obj.search(cr, uid, [('name', '=', record[header.index(u'快递方式')])], context=context):
                    raise osv.except_osv(u'错误', u'输入的快递方式 %s 不存在' % record[
                                         header.index(u'快递方式')])
                # 如果用户修改了卡券号这一列，或者增加了行，报错
                if not delivery_obj.search(cr, uid, [('copy_code', '=', record[header.index(u'卡号')]), ('is_export', '=', True)], context=context):
                    raise osv.except_osv(u'错误', u'输入的卡券号 %s 未导出' % record[
                                         header.index(u'卡号')])
                # 券号、单号、快递方式都输入了才算有效记录
                if all([record[header.index(u'卡号')], record[header.index(u'快递方式')], record[header.index(u'快递单号')]]):
                    # 之前导入过的数据再次导入不报错，直接忽略
                    delivery_id = delivery_obj.search(
                        cr, uid, [('copy_code', '=', record[header.index(u'卡号')])], context=context)
                    apply_deliverobj = delivery_obj.browse(
                        cr, uid, delivery_id, context=context)
                    users = user_obj.browse(cr, uid, uid, context=context)
                    if apply_deliverobj.assigned_shop_id:
                        if apply_deliverobj.assigned_shop_id.id != uid:
                            raise osv.except_osv(u'错误', u'卡券号 %s不在您的发货记录里边 ' % record[
                                                 header.index(u'卡号')])
                    elif not users[0].has_group('dzx_ext.group_call_center'):
                        raise osv.except_osv(u'错误', u'卡券号 %s不在您的发货记录里边 ' % record[
                                             header.index(u'卡号')])
                    to_import.append([record[header.index(u'卡号')], record[
                                     header.index(u'快递方式')], record[header.index(u'快递单号')]])

        if selected > 0:
            selected -= 1
        imported = len(to_import)
        vals = {'state': '2',
                'selected': selected,
                'imported': imported,
                'to_import': to_import}

        self.write(cr, uid, ids, vals, context=context)

        return {
            'type': 'ir.actions.act_window',
            'res_model': 'apply.import.wizard',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': this_id,
            'views': [(False, 'form')],
            'target': 'new',
        }

    def button_ok(self, cr, uid, ids, context=None):
        delivery_obj = self.pool.get('apply.delivery')
        express_obj = self.pool.get('express.type')
        move_obj = self.pool.get('account.move')
        to_import = eval(self.browse(cr, uid, ids, context=context).to_import)
        if not to_import:
            raise osv.except_osv(u'错误', u'文件中没有需要导入的行')
        for code, express, number in to_import:
            delivery_ids = delivery_obj.search(
                cr, uid, [('copy_code', '=', code)], context=context)
            express_id = express_obj.search(
                cr, uid, [('name', '=', express)], context=context)[0]
            delivery_ship_obj = delivery_obj.browse(
                cr, uid, delivery_ids, context=context)
            # 以此判断来判断是否是门店修改快递方式。如果是修改就不再改变is_shipping。从而可以避免多次生成补助费用。
            context.update({'delay': True})
            if delivery_ship_obj.is_shipping:
                delivery_obj.write(cr, uid, delivery_ids,
                                   {'shipping_code': long(
                                       number), 'shipping_type': express_id},
                                   context=context)
            else:
                moves = delivery_obj.write(cr, uid, delivery_ids,
                                           {'shipping_code': long(
                                               number), 'shipping_type': express_id, 'is_shipping': True},
                                           context=context)
                if moves:
                    move_obj.button_validate(cr, 1, moves, context)
        return True
